//
//  YLProductDetaiHeaderViewModel.m
//  YLFinanceService
//
//  Created by she1323 on 2017/8/28.
//  Copyright © 2017年 she1323. All rights reserved.
//  定期理财

#import "YLProductDetailViewModel.h"
#import "WHNetworkTool.h"
#import "WHProgressHUD.h"
#import "YLAccountTool.h"
#import "YLProductItems.h"
#import "YLProductModel.h"
@implementation YLProductDetailViewModel


- (instancetype)init
{
    if (self = [super init]) {
        _productIntroductionSubject = [RACSubject subject];
        _relevantAgreementSubject = [RACSubject subject];
        _collectionCalculatorSubject = [RACSubject subject];
        [self setUp];
    }
    return self;
}

- (void)setUp
{
     __weak typeof(self) weakSelf = self;
    _requestCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
       
       
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            NSMutableDictionary *parmas = [NSMutableDictionary dictionaryWithCapacity:12];
            parmas[@"PageIndex"] = @(1); // 请求页数，1开始
            parmas[@"MaxResultCount"] = @(1); // 每页条数
            parmas[@"Sorting"] = @""; // 排序键值
            parmas[@"SearchProductCategory"] = @(-1); // 产品类型 企来贷 = 1, 易收益 = 2, -1
            parmas[@"SearchPayCategory"] = @(-1); // 兑付方式 到期分配 = 0, 按月分配 = 1, 半年分配 = 6， -1
            parmas[@"SearchProductTerm"] = @(-1); // 产品期限  3 6 12 18 24 -1
            parmas[@"IsHomeList"] = @(0); // 列表
            parmas[@"PromotionPlatformType"] = @(0); // 所有平台
            parmas[@"YieldFrom"] = @(-1); // 利率从，-1表示不限
            parmas[@"YieldTo"] = @(-1); // 利率至，-1表示不限
            parmas[@"SearchProductCode"] = input;
            
            
            NSString *url = [NSString stringWithFormat:@"%@Product/PGetProductList", YLURL];
            
            [[WHNetworkTool shareInstance] sendPostWithUrl:url header:[YLAccountTool header] params:parmas success:^(id responseObject) {
                
                
                if ([responseObject[@"httpCode"] integerValue] == 200) {
                    YLProductItems *productItems = [YLProductItems yy_modelWithDictionary:responseObject[@"httpResult"]];
                    
                    weakSelf.model = productItems.items.firstObject;
//                    weakSelf.model.indexLimit = 100;
                    
                    [weakSelf setUpHeaderModel:weakSelf.model];
                    
                    [subscriber sendNext:nil];
                 
                    
                } else {
                    [WHProgressHUD showError:responseObject[@"message"]];
                }
                [subscriber sendCompleted];
                
                
            } fail:^(NSError *error) {
                [subscriber sendCompleted];
            }];
            
            return nil;
        }];
        
    }];
}


- (void)setUpHeaderModel:(YLProductModel *)model
{
    _headerModel = [[YLProductDetaiHeaderModel alloc] init];
    // 年化收益
    _headerModel.rateOfReturn =  [NSString stringWithFormat:@"%@%%", model.annualizedYield];
    
    // 进度条
    if (model.maxLimit == 0) {
        _headerModel.investmentPercentage = 0;
    } else {
        _headerModel.investmentPercentage = (model.maxLimit - model.indexLimit) / model.maxLimit * 100;
    }
    
    NSString *leastMoney = @"";
    if (model.leastMoney > 9999) {
        leastMoney = [NSString stringWithFormat:@"%.2f万元",model.leastMoney / 10000.0];
    } else {
        leastMoney = [NSString stringWithFormat:@"%.2f", model.leastMoney];
    }
    
    NSString *productTerm = [NSString stringWithFormat:@"%zd个月", model.productTerm];
    
    NSString *payCategory = @"";
    switch (model.payCategory) {
        case 0:
            payCategory = @"到期分配";
            break;
            
        case 1:
            payCategory = @"按月分配";
            break;
            
        case 6:
            payCategory = @"半年分配";
            break;
            
    }
    
    _headerModel.detailHeaderTitles = @[[YLProductHeaderTitleModel
                                         modelWithContent:leastMoney title:@"起投"],
                                        [YLProductHeaderTitleModel modelWithContent:productTerm title:@"期限"],
                                        [YLProductHeaderTitleModel modelWithContent:payCategory title:@"兑付方式"]];
}

- (YLProductDetaiHeaderModel *)headerModel
{
    if (!_headerModel) {
        _headerModel = [[YLProductDetaiHeaderModel alloc] init];

    }
    return _headerModel;
}

- (NSArray *)items
{
    if (!_items) {
        __weak typeof(self) weakSelf = self;
        _items = @[
                   [YLIconTitleModel modelWithIcon:@"ProductIntroduction" title:@"产品介绍" clickBlock:^NSString *{
                       [weakSelf.productIntroductionSubject sendNext:nil];
                       return nil;
                   }],
                   [YLIconTitleModel modelWithIcon:@"CollectionDetails" title:@"收款计算器" clickBlock:^NSString *{
                       [weakSelf.collectionCalculatorSubject sendNext:nil];
                       return nil;
                   }],
                   [YLIconTitleModel modelWithIcon:@"RelevantAgreement" title:@"相关协议" clickBlock:^NSString *{
                       [weakSelf.relevantAgreementSubject sendNext:@"222"];
                       return nil;
                   }]
                   ];
    }
    return _items;

}

- (RACCommand *)buyCommand
{
    if (!_buyCommand) {
        __weak typeof(self) weakSelf = self;
        _buyCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
                if (!weakSelf.model) {
                    [subscriber sendCompleted];
                    return nil;
                }
                
                NSString *url = [NSString stringWithFormat:@"%@Product/ProductReservation", YLURL];
                
                [[WHNetworkTool shareInstance] sendPostWithUrl:url header:[YLAccountTool header] params:@{@"Id" : weakSelf.model.productId, @"ReservationAmount" : input} success:^(id responseObject) {
                    [WHProgressHUD dismiss];
                    if ([responseObject[@"httpCode"] integerValue] == 200) {
                        [subscriber sendNext:nil];
                        
                    } else {
                        [WHProgressHUD showError:responseObject[@"message"]];
                        [subscriber sendNext:@(1)];
                    }
                    [subscriber sendCompleted];
                    
                } fail:^(NSError *error) {
                    [subscriber sendNext:@(1)];
                    [subscriber sendCompleted];
                }];
                
               
                return nil;
            }];
            
        }];
    }
    return _buyCommand;
    
}


- (void)dealloc
{
    [[WHNetworkTool shareInstance] cancel];
    [WHProgressHUD dismiss];
}


@end
